package cn.nexd.demo.location.collection;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.nexd.location.NexdLocationAgent;
import cn.nexd.location.NexdLocationConfig;
import cn.nexd.location.NexdLocationListener;
import cn.nexd.location.collector.bean.WifiCollectorResult;
import cn.nexd.location.collector.core.Collector;


public class MainActivity extends Activity implements View.OnClickListener, NexdLocationListener, Collector.WifiCollectorListener {


    private Button startWifiLocationButton = null;
    private Button stopWifiLocationButton = null;
    private NexdLocationAgent nexdLocationAgent;
    private List<Map<Long, LocationResult>> results = new ArrayList<Map<Long, LocationResult>>();
    private Map<Long, LocationResult> map = new HashMap<Long, LocationResult>();
    private TextView showMessage;
    private float lastX;
    private float lastY;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nexdLocationAgent = NexdLocationAgent.getLocationAgent();
        nexdLocationAgent.setContext(this);
        NexdLocationConfig.Buidler buidler = new NexdLocationConfig.Buidler();
        buidler.setAppkey("");
        buidler.setLocationRate(1000);
        buidler.setSmoothness(false);
        //        buidler.setLocationMode(NexdLocationConfig.LocationMode.BLUETOOTH_ONLY);
        buidler.setLocationMode(NexdLocationConfig.LocationMode.BLUETOOTH_ONLY);
        nexdLocationAgent.setLocationConfig(buidler.build());
        nexdLocationAgent.setLocationListener(this);
        nexdLocationAgent.setWifiCollectorListener(this);

        startWifiLocationButton = (Button) findViewById(R.id.btn_wifi_location);
        startWifiLocationButton.setOnClickListener(this);

        stopWifiLocationButton = (Button) findViewById(R.id.btn_stop_location);
        stopWifiLocationButton.setOnClickListener(this);

        showMessage = (TextView) findViewById(R.id.textView);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "设备不支持蓝牙4.0", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        nexdLocationAgent.destroy();
    }

    @Override
    public void onClick(View v) {
        if (startWifiLocationButton.getId() == v.getId()) {
            File file = new File("/sdcard/nexd/map/10108058/10108058.mean");
            if (!file.exists()) {
                //不存在
                copyAssets("10108058", "/sdcard/nexd/map/10108058/");
            }
            //            nexdLocationAgent.startLocation(10108106L);
            nexdLocationAgent.startLocation(10108058, 101080580001L);
            //            nexdLocationAgent.startLocation(10108106L, 101081060001L);
            //            nexdLocationAgent.startLocation(10100123L);
            //            nexdLocationAgent.startLocation(10100123L, 101001230001L);
        } else if (stopWifiLocationButton.getId() == v.getId()) {
            nexdLocationAgent.stopLocation();
        }
    }

    @Override
    public void onLocationStart() {
        Log.d("collector_test", "onLocationStart");
    }

    @Override
    public void onLocationSuccess(long locationTaskId, final cn.nexd.location.LocationResult locationResult) {
        Log.d("collector_test", "" + locationResult.toString());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMessage.setText("X 轴 " + (locationResult.getLocationResultX() - 20) + "    Y 轴 " + (locationResult.getLocationResultY() - 20) + "  误差 (" + (locationResult.getLocationResultX() - 20 - lastX) + " " + (locationResult.getLocationResultY() - 20 - lastY) + ")");
                lastX = locationResult.getLocationResultX() - 20;
                lastY = locationResult.getLocationResultY() - 20;
            }
        });
    }

    @Override
    public void onLocationFailed(int locationResultFailedMessageType, String locationResultFailedMessage) {
        Log.d("collector_test", "onLocationFailed  type == " + locationResultFailedMessageType + " message ==  " + locationResultFailedMessage);
    }

    @Override
    public void onLocationInterrupt(int locationInterruptType, String locationInterruptMessage) {
        Log.d("collector_test", "onLocationInterrupt  type == " + locationInterruptType + " message ==  " + locationInterruptMessage);

    }

    private void copyAssets(String assetDir, String dir) {
        String[] files;
        try {
            files = this.getResources().getAssets().list(assetDir);
        } catch (IOException e1) {
            return;
        }
        File mWorkingPath = new File(dir);
        //if this directory does not exists, make one.
        if (!mWorkingPath.exists()) {
            if (!mWorkingPath.mkdirs()) {

            }
        }

        for (int i = 0; i < files.length; i++) {
            try {
                String fileName = files[i];
                //we make sure file name not contains '.' to be a folder.
                if (!fileName.contains(".")) {
                    if (0 == assetDir.length()) {
                        copyAssets(fileName, dir + fileName + "/");
                    } else {
                        copyAssets(assetDir + "/" + fileName, dir + fileName + "/");
                    }
                    continue;
                }
                File outFile = new File(mWorkingPath, fileName);
                if (outFile.exists())
                    outFile.delete();
                InputStream in = null;
                if (0 != assetDir.length())
                    in = getAssets().open(assetDir + "/" + fileName);
                else
                    in = getAssets().open(fileName);
                OutputStream out = new FileOutputStream(outFile);

                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                in.close();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onFailed(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskFailedType, String collectorResultTaskFailedMessage) {
        Log.d("collector_test", "" + collectorResultTaskId + "  " + collectorResultTaskTime + "  " + collectorResultTaskFailedMessage);

    }

    @Override
    public void onSuccess(long collectorResultTaskId, long collectorResultTaskTime, List<WifiCollectorResult> wifiCollectorResults) {
        Log.d("collector_test", "" + collectorResultTaskId + "  " + collectorResultTaskTime + "  " + wifiCollectorResults.size());
    }

    @Override
    public void onStop(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskStopType, String collectorResultTaskStopMessage) {
        Log.d("collector_test", "" + collectorResultTaskId + "  " + collectorResultTaskTime + "  " + collectorResultTaskStopMessage);
    }
}